package ten;

public class LockTest01 {

    ReLock lock = new ReLock();

    public void a() throws InterruptedException {
        lock.lock();
        System.out.println(lock.getHoldCount());
        doSomething();
        lock.unlock();
    }

    private void doSomething() throws InterruptedException {
        lock.lock();
        System.out.println(lock.getHoldCount());
        System.out.println("doSomething");
        lock.unlock();
    }

    public void test() {
        synchronized (this) {
            while (true) {
                synchronized (this) {
                    System.out.println("ReentrantLock!");
                }
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    public static void main(String[] args) throws InterruptedException {
//        new LockTest01().test();
        LockTest01 test = new LockTest01();
        test.a();
        test.doSomething();
        Thread.sleep(1000);
        System.out.println(test.lock.getHoldCount());
    }
}

class ReLock {
    //是否占用
    private boolean isLocked = false;
    Thread lockedBy = null;
    private int holdCount = 0;

    public int getHoldCount() {
        return holdCount;
    }

    //使用锁
    public synchronized void lock() throws InterruptedException {
        Thread t = Thread.currentThread();
        while (isLocked && lockedBy != t) {
            wait();
        }
        isLocked = true;
        lockedBy = t;
        holdCount++;
    }

    public synchronized void unlock() {
        if(Thread.currentThread() == lockedBy) {
            holdCount--;
            if(holdCount == 0) {
                isLocked = false;
                notify();
                lockedBy = null;
            }
        }
    }
}